﻿using AutoMapper;
using MediatR;
using Traceability.App.API.Application.Command.Supplier;
using Traceability.App.Domain.Traceability;
using Traceability.App.ErrorCode;
using Traceability.App.Infrastructrue.Interface;

namespace Traceability.App.API.Application.Handler.Supplier
{
    public class CreateSupplierHandler : IRequestHandler<CreateSupplierCommand, APIResult<int>>
    {
        private readonly IBaseRepository<SupplierModel> supplierRepo;
        private readonly IMapper mapper;

        public CreateSupplierHandler(IBaseRepository<SupplierModel> supplierRepo,
                                    IMapper mapper)
        {
            this.supplierRepo = supplierRepo;
            this.mapper = mapper;
        }
        public Task<APIResult<int>> Handle(CreateSupplierCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var model = mapper.Map<SupplierModel>(request);
            int r = supplierRepo.AddAsync(model).Result;
            if (r > 0)
            {
                result.Message = "设置供应商基本信息成功";
                result.Data = r;
                result.Code = APIEnum.Ok;
            }
            else
            {
                result.Message = "设置供应商基本信息失败";
                result.Data = r;
                result.Code = APIEnum.Fail;
            }
            return Task.FromResult(result);
        }
    }
}
